﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Text.RegularExpressions;
using System.ComponentModel;

namespace TA.Turbo.Controls
{
	/// <summary>
	/// Validates a control by testing its value using a Regex.
	/// </summary>
	public class RegexValidator : BaseValidator
	{
		#region PUBLIC
		#region INIT
		public RegexValidator()
		{
		}
		#endregion
		#region PROPS
		#region DEF
		/// <summary>
		/// Props.
		/// </summary>
		protected static new Properties _clientProperties = Define(BaseValidator._clientProperties,
			new[] {
				new PropertyDefinition<string>("Regex", "R", ""),
			});
		/// <summary>
		/// Props.
		/// </summary>
		public override Properties ClientProperties
		{
			get
			{
				return _clientProperties;
			}
		}
		#endregion
		/// <summary>
		/// The regular expression to use for validation.
		/// </summary>
		[DefaultValue("")]
		public string Regex
		{
			get
			{
				return GetProperty<string>("Regex");
			}
			set
			{
				ViewState["Regex"] = value;
			}
		}
		#endregion
		#endregion
		#region INTERNAL
		#region METHODS
		#region INIT
		/// <summary>
		/// Registers RegexValidator.js.
		/// </summary>
		protected internal override void RegisterIncludes(IncludeCollection includes)
		{
			base.RegisterIncludes(includes);

			includes.Add(Script.String_IsNullOrEmpty);
			includes.Add(new ScriptResourceInclude("TA.Turbo.Res.JS.Validators.RegexValidator.js", typeof(RegexValidator)));
		}
		#endregion
		#region VALIDATION
		/// <summary>
		/// Performs the validation.
		/// </summary>
		protected override void DoValidate()
		{
			if (string.IsNullOrEmpty(Regex) || this.ValidatedControl == null)
				SetValidStatus(true);
			else
			{
				string value = "";
				if (this.ValidatedControl is FileUpload)
				{
					value = ((FileUpload)this.ValidatedControl).Value.Name;
				}
				else if (this.ValidatedControl.GenericValue != null)
				{
					value = this.ValidatedControl.GenericValue.ToString();
				}
				SetValidStatus(new Regex(Regex).IsMatch(value));
			}
		}
		#endregion
		#endregion
		#endregion
	}
}
